
class Node(object):
    def __init__(self):
        self.left = None
        self.right = None
        self.data = None


class tree(object):
    def __init__(self, l):
        assert isinstance(l, (list, tuple))
        # 创建一个根节点
        self.root = None
        # 用于计算列表的长度
        self.count = 0

        if l:
            self.root = self.build(l, 0, len(l) - 1)

    # 创建一个树结构，传入三个参数，列表，列表的最小索引和最大索引值
    def build(self, l, min, max):
        self.count += 1
        # 寻找中间索引值
        middle = (min + max) // 2

        # new一个中间的数
        node = Node()
        node.data = l[middle]
        if middle > min:
            node.left = self.build(l, min, middle - 1)
        if middle < max:
            node.right = self.build(l, middle+1, max)

        print('creat node %d' % node.data)
        return node

    def __len__(self):
        return self.count

    def _forach(self, node):
        if node is None:
            return

        if node.left:
            self._forach(node.left)

        if node.right:
            self._forach(node.right)

    def loop(self):
        self._forach(self.root)


if __name__ == "__main__":
    l = (2, 3, 4, 5, 6, 7, 8)
    b = tree(l)
    b.loop()